/**
 * Created by HTWX on 2018/3/19.
 */
var express = require('express');
var router = express.Router();
var BaseModel = require('../models/base_model');
var baseModel = new BaseModel();
var Q=require('q');

function loginone(req,res){
    var deferred = Q.defer();
    var sql = "select report_id,user_id,yk_report.paper_id,yk_paper.papercount,admincard,papername,papertime,paperscore from yk_report,yk_paper where yk_report.paper_id=yk_paper.paper_id and admincard='"+req.query.id+"'";
    console.log(sql);
    baseModel.findOneById(sql,function(ret){
        if(ret)
        {
            res.cookie('report_id',ret.report_id, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('paper_id',ret.paper_id, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('user_id',ret.user_id, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('papercount',ret.papercount, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('paperscore',ret.paperscore, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('admincard',ret.admincard, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('papername',ret.papername, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('papertime',ret.papertime, {maxAge:100000*6000, path:'/', httpOnly:false});
        }
        deferred.resolve(ret);
    });
    return deferred.promise;
}

function logintwo(req,res){
    var deferred = Q.defer();
    var sql = "select username,credentials from yk_user where tel='"+  req.cookies.ownuser  + "'";
    console.log(sql);
    baseModel.findOneById(sql,function(ret){
        if(ret)
        {
            res.cookie('username',ret.username, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('credentials',ret.credentials, {maxAge:100000*6000, path:'/', httpOnly:false});
        }
        deferred.resolve(ret);
    });
    return deferred.promise;
}

router.get('/',function(req, res) {
    Q.all([loginone(req,res),logintwo(req,res)]).spread(function(rs1,rs2){
        if(rs1&&rs2){
            res.cookie('report','', {maxAge:100000*6000, path:'/', httpOnly:false});
            var myDate = new Date();
            res.cookie('start',myDate.toLocaleString(), {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('num',1, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('page',1, {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('min','', {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('max','', {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('submits','N', {maxAge:100000*6000, path:'/', httpOnly:false});
            res.cookie('mark','', {maxAge:100000*6000, path:'/', httpOnly:false});
            res.redirect('/main');
        }else{
            res.redirect('/main');
        }
    });
});

module.exports = router;